package com.example.jetpacktest.work

import android.app.Notification
import android.app.PendingIntent
import android.content.Context
import android.util.Log
import androidx.work.CoroutineWorker
import androidx.work.ForegroundInfo
import androidx.work.WorkManager
import androidx.work.WorkerParameters
import com.example.jetpacktest.R
import kotlinx.coroutines.delay

class MyWork004(appContext: Context, params: WorkerParameters) : CoroutineWorker(appContext, params) {

    private val TAG: String = this.javaClass.simpleName

    override suspend fun doWork(): Result {
        Log.d(TAG, "MyWork004开始..........")

        val url: String? = inputData.getString(KEY_URL)
        val outputFileName: String? = inputData.getString(KEY_OUTPUT_FILE_NAME)
        Log.d(TAG, "url = $url")
        Log.d(TAG, "outputFileName = $outputFileName")

        setForeground(createForegroundInfo("download progress"))
        download()

        Log.d(TAG, "MyWork004结束..........")
        return Result.success()
    }


    private suspend fun download(){
        Log.d(TAG, "download()开始........")
        delay(2 * 60 * 1000)
        Log.d(TAG, "download()结束........")
    }


    private fun createForegroundInfo(progress: String): ForegroundInfo{
        val workManager: WorkManager = WorkManager.getInstance(applicationContext)
        val intent: PendingIntent = workManager.createCancelPendingIntent(id)
        val notification: Notification = Notification.Builder(applicationContext)
            .setContentTitle("myContentTitle")
            .setTicker("myTicker")
            .setContentText(progress)
            .setSmallIcon(R.drawable.ic_launcher_foreground)
            .setOngoing(true)
            .addAction(R.drawable.ic_launcher_background, "actionTitle", intent)
            .build()
        return ForegroundInfo(123, notification)
    }


    companion object{
        const val KEY_URL = "KEY_URL"
        const val KEY_OUTPUT_FILE_NAME = "KEY_OUTPUT_FILE_NAME"
    }

}